package com.jw.springboot_jw.controller;

import com.jw.springboot_jw.pojo.ResponseMessage;
import com.jw.springboot_jw.pojo.User;
import com.jw.springboot_jw.pojo.dto.UserDto;
import com.jw.springboot_jw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author wuJiaWei
 * @version 1.0
 */
@RestController //接口方法返回对象,对象会直接转换成json文本
@RequestMapping("/user")    //接口路径 localhost:8088/user
public class UserController {

    //自动装配进来
    @Autowired
    UserService userService;//注入service层


    //RESTFul风格
    /**
     * 增加
     * @return
     * //@Validated:参数校验
     * //@RequestBody:请求体,将请求体中的json数据转换成java对象.传进来的是一个json文本,会自动转成对象
     * //UserDto:java对象,用于接收请求体中的数据。与User实体类进行区分。
     */
    @PostMapping //URL:localhost:8088/user method:post
    public ResponseMessage<User> add(@Validated @RequestBody UserDto userDto){
        User userNew = userService.add(userDto);
        return ResponseMessage.success(userNew);
    }

    /**
     * 查询
     * //ResponseMessage<User>:返回值类型,返回一个ResponseMessage对象,泛型为User
     * //@PathVariable:路径变量,从路径中获取参数
     */
    @GetMapping("/{userId}")    //URL:localhost:8088/user/1 method:get
    public ResponseMessage<User> get(@PathVariable Integer userId){
        User user = userService.get(userId);
        return ResponseMessage.success(user);
    }
    //修改
    @PutMapping
    public ResponseMessage<User> update(@Validated @RequestBody UserDto userDto){
        User userNew = userService.update(userDto);
        return ResponseMessage.success(userNew);
    }
    //删除
    @DeleteMapping("/{userId}")
    public ResponseMessage<User> delete(@PathVariable Integer userId){
        userService.delete(userId);
        return ResponseMessage.success(null);
    }

}
